package com.peter.ai.voice;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.json.JSONObject;

import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.baidu.aip.util.Util;

public class BaiduClientIntance {
	// 设置APPID/AK/SK
	public static final String APP_ID = "16613971";
	public static final String API_KEY = "LcrrtK4pGtI5e1o9Gglmg3GT";
	public static final String SECRET_KEY = "6YvT9XEiOcHp0rK1mLfrw6Dojmj5ybEw";

	private AipSpeech client;

	public AipSpeech getInstance() {
		if (client == null) {
			// 初始化一个AipSpeech
			client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
			// 可选：设置网络连接参数
			client.setConnectionTimeoutInMillis(2000);
			client.setSocketTimeoutInMillis(60000);
		}
		return client;
	}

	public void text2Voice(String title, String text, String voicePath) {
		if (voicePath == null || voicePath == "") {
			voicePath = "E://text2voice/mp3/";
		}
		BaiduClientIntance baiduClientIntance = new BaiduClientIntance();

		// 初始化一个AipSpeech
		AipSpeech client = baiduClientIntance.getInstance();
		// 设置可选参数
		HashMap<String, Object> options = new HashMap<String, Object>();
	    options.put("spd", "5");//语速，取值0-9，默认为5中语速
	    options.put("pit", "5");//音调，取值0-9，默认为5中语调
	    options.put("vol", "5");//音量，取值0-15，默认为5中音量
	    options.put("per", "0");//发音人选择, 0为女声，1为男声，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女
		// 调用接口
		TtsResponse res = client.synthesis(text, "zh", 1, options);
		byte[] data = res.getData();
		JSONObject res1 = res.getResult();
		if (data != null) {
			try {
				File file = new File(voicePath);
				if (!file.exists()) {
					file.mkdirs();
				}

				Util.writeBytesToFileSystem(data, voicePath + title + ".mp3");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (res1 != null) {
			System.out.println(res1.toString(2));
		}
	}

}